package com.itbaizhan.ruiji.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itbaizhan.ruiji.dto.DishDto;
import com.itbaizhan.ruiji.mapper.DishMapper;
import com.itbaizhan.ruiji.pojo.Dish;
import com.itbaizhan.ruiji.pojo.DishFlavor;
import com.itbaizhan.ruiji.service.DishFlavorService;
import com.itbaizhan.ruiji.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DishImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;
    @Override
    @Transactional
    public void savewithflavor(DishDto dishDto) {
        this.save(dishDto);
        log.info("保存菜品信息：{}",dishDto);
        Long dishid = dishDto.getId();
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors.forEach(flavor -> flavor.setDishId(dishid));
        dishFlavorService.saveBatch( flavors);
    }

    @Override
    public DishDto getByidWithFlavor(@PathVariable long id) {
        Dish dish = this.getById(id);
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,id);
        List<DishFlavor> list = dishFlavorService.list(queryWrapper);
        dishDto.setFlavors(list);
        return dishDto;

    }

    @Override
    @Transactional
    public void updatewithflavor(DishDto dishDto) {
        this.updateById(dishDto);
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(queryWrapper);
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors=flavors.stream().map(flavor -> {
            Long id = dishDto.getId();
            flavor.setDishId(id);
            return flavor;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(flavors);

    }
}
